package com.hejing.Collection子接口Set;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * ClassName: TreeSetTest
 * Package: com.hejing.Collection子接口Set
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-05-18 16:22
 * @Version: 1.0
 */
public class TreeSetTest {
    
    // 添加String
    // 自然排序
    @Test
    public void test01() {

        Set set = new TreeSet();

        set.add("AA");
        set.add("BB");
        set.add("CC");
        set.add("DD");
        set.add("EE");
        set.add("MM");

        /*
         * 注意，TreeSet与前面的HashSet和LinkedHashSet不同，添加的元素必须是同一类型，因为TreeSet涉及到了按照添加的元素
         * 的某一个属性的大小进行排序遍历
         * */
        // set.add(123); 报错: java.lang.ClassCastException

        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
    
    // 添加自定义类型对象
    // 自然排序:
    @Test
    public void test02(){

        TreeSet set = new TreeSet();
        User u1 = new User("Tom", 23);
        User u2 = new User("Luffy", 25);
        User u3 = new User("Jack", 18);
        User u4 = new User("LiHua", 23);
        User u5 = new User("HanMeiMei", 33);

        set.add(u1);
        set.add(u2);
        set.add(u3);
        set.add(u4);
        set.add(u5);

        // 遍历:
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    // 定制排序:
    @Test
    public void test03(){

        /**
         * 按照姓名从小到大排序，姓名相同，按照年龄从大到小排列
         */
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    int value = u1.getName().compareTo(u2.getName());
                    if(value != 0) {
                        return value;
                    }
                    return -(u1.getAge() - u2.getAge());
                }
                throw new RuntimeException("类型不匹配");
            }
        };

        TreeSet set = new TreeSet(comparator);

        User u1 = new User("Tom", 23);
        User u2 = new User("Luffy", 25);
        User u3 = new User("Jack", 18);
        User u4 = new User("LiHua", 23);
        User u5 = new User("HanMeiMei", 33);

        set.add(u1);
        set.add(u2);
        set.add(u3);
        set.add(u4);
        set.add(u5);

        // 遍历:
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    }
}





















